package com.ambitor.ipro.app.count;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.LocalConnectionUtils;
import com.ambitor.ipro.util.TableName;

public class ItemIdParser implements Runnable {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private SuperDao superDao = null;

	public void run() {
		while (true) {
			execute();
		}
	}

	@SuppressWarnings("unchecked")
	private void execute() {
		Connection conn = null;
		try {
			conn = getConnection();
			superDao = new SuperDaoImpl(conn);
			IDataset dataset = fetchNotDealedPv();
			if (dataset == null || dataset.size() == 0) {
				logger.info("没找到未处理的pv记录，休息一会");
				long interval = Long.parseLong(CountPropertiesReader
						.getString("PARSER_INTEVAL"));
				sleep(interval); // 休息5分钟
				return;
			}
			logger.info("找到" + dataset.size() + "条pv记录，开始处理");
			for (int i = 0; i < dataset.size(); i++) {
				IData pvMap = dataset.getData(i);
				String url = pvMap.getString("URL");
				String iid = parseUrlAndGetIid(url);
				pvMap.put("IID", iid);
				String fromIid = parseUrlAndGetFromIid(url);
				pvMap.put("FROM_IID", fromIid);
				pvMap.put("DEAL_TAG", "1");
				pvMap.remove("URL");
			}
			try {
				superDao.update(TableName.TL_S_PV, dataset);
			} catch (Exception e) {
				logger.error("保存parseReferer数据失败", e);
			}
		} catch (Exception e) {
			logger.error("解析url中iid的过程中发生异常", e);
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.warn("conn.close()出现异常", e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private IDataset fetchNotDealedPv() {
		int batchNum = Integer.parseInt(CountPropertiesReader
				.getString("BATCH_PV_NUM"));
		// String sql = "(select pv_id,url from " + TableName.TL_S_PV + " where"
		// + " visit_time between :CLCT_DAY_START and :CLCT_DAY_END "
		// + " and deal_tag = :DEAL_TAG limit :BATCH_NUM)";
		String sql = "(select pv_id,url from " + TableName.TL_S_PV + " where"
				+ " deal_tag = :DEAL_TAG limit :BATCH_NUM)";
		IData param = new DataMap();
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		// Date date = new Date();
		// String clctStart = sdf.format(date);
		// sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		// String clctEnd = sdf.format(date);
		// param.put("CLCT_DAY_START", clctStart);
		// param.put("CLCT_DAY_END", clctEnd);
		param.put("DEAL_TAG", "0");
		param.put("BATCH_NUM", batchNum);
		IDataset dataset = null;
		try {
			dataset = superDao.queryListBySql(sql, param);
		} catch (Exception e) {
			logger.error("查询当天新增pv数据失败", e);
		}
		return dataset;
	}

	private String parseUrlAndGetIid(String url) {
		String iid = "";
		String regex = "\\?id=[\\d]{10,15}";
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(url);
		if (m.find()) {
			iid = m.group();
			iid = iid.replace("?id=", StringUtils.EMPTY);
		}
		return StringUtils.trimToEmpty(iid);
	}

	private String parseUrlAndGetFromIid(String url) {
		String iid = "";
		String regex = "from_id=[\\d]{10,15}";
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(url);
		if (m.find()) {
			iid = m.group();
			iid = iid.replace("from_id=", StringUtils.EMPTY);
		}
		return StringUtils.trimToEmpty(iid);
	}

	private Connection getConnection() {
		Connection conn = null;
		int tryTimes = 0;
		while (tryTimes < Constants.TAOBAO_API_CALL_MAX_TIMES) {
			try {
				conn = LocalConnectionUtils.getConnection();
				break;
			} catch (SQLException e) {
				logger.error("获取Connection出现异常");
				tryTimes++;
				sleep(500);
			}
		}
		return conn;
	}

	private void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException exp) {
		}
	}
}
